import { useState, useEffect } from "react";
import { CustomTitlebar } from "./CustomTitlebar";
import { PasswordManager } from "./PasswordManager";
import PasswordSetup from "./PasswordSetup";
import PasswordLogin from "./PasswordLogin";
import { LogViewer } from "./LogViewer";
import { ChangeMasterPassword } from "./ChangeMasterPassword";
import ModelManagement from "./ModelManagement";
import AIChat from "./AIChat";
import { useAuth } from "@/contexts/AuthContext";
import { logger } from "@/utils/logger";

type ActiveModule = "welcome" | "passwords" | "ai-models" | "ai-chat" | "settings";

export function Dashboard() {
  const [activeModule, setActiveModule] = useState<ActiveModule>("welcome");
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" | "info" } | null>(null);
  const [showPasswordAuth, setShowPasswordAuth] = useState(false);
  const [showLogViewer, setShowLogViewer] = useState(false);
  const { isAuthenticated, hasMasterPassword, isLoading } = useAuth();

  logger.debug('[Dashboard] ====== RENDER ======', { isAuthenticated, hasMasterPassword, isLoading, showPasswordAuth });

  // Debug: Log auth state changes
  useEffect(() => {
    logger.info('[Dashboard] ****** Auth state changed', { isAuthenticated, hasMasterPassword, isLoading });
  }, [isAuthenticated, hasMasterPassword, isLoading]);
  
  // Log on mount
  useEffect(() => {
    logger.info('[Dashboard] >>>>>> Dashboard mounted');
  }, []);

  // 添加快捷键监听：Ctrl+Shift+L 打开日志查看器
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (e.ctrlKey && e.shiftKey && e.key === 'L') {
        e.preventDefault();
        setShowLogViewer(prev => !prev);
      }
    };

    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, []);

  const showToast = (message: string, type: "success" | "error" | "info") => {
    setToast({ message, type });
    setTimeout(() => setToast(null), 3000);
  };

  const handlePasswordModuleClick = () => {
    logger.info('[Dashboard] ========== PASSWORD MODULE CLICKED ==========');
    logger.info('[Dashboard] Current state', { hasMasterPassword, isAuthenticated, isLoading, showPasswordAuth });
    
    // Wait for loading to complete before showing auth dialog
    if (isLoading) {
      logger.info('[Dashboard] Still loading, waiting...');
      return;
    }
    
    // Always open the auth dialog and let the modal's conditional rendering
    // determine which component to show based on the CURRENT hasMasterPassword state
    if (!isAuthenticated) {
      logger.info('[Dashboard] Not authenticated, showing auth dialog');
      logger.info('[Dashboard] hasMasterPassword value: ' + hasMasterPassword);
      setShowPasswordAuth(true);
    } else {
      logger.info('[Dashboard] Already authenticated, entering password manager');
      setActiveModule("passwords");
    }
    logger.info('[Dashboard] ========== END PASSWORD MODULE CLICKED ==========');
  };

  const handleAuthSuccess = () => {
    logger.info('[Dashboard] ========== AUTH SUCCESS ==========');
    setShowPasswordAuth(false);
    setActiveModule("passwords");
  };

  return (
    <div className="h-screen flex flex-col bg-background">
      {/* Custom Titlebar */}
      <CustomTitlebar
        onSettingsClick={() => setActiveModule("settings")}
        onInfoClick={() => showToast("密码管理器 v1.0.0", "info")}
        onLogViewerClick={() => setShowLogViewer(prev => !prev)}
      />

      <div className="flex-1 flex overflow-hidden">
        {/* Sidebar Navigation */}
        <div className="w-60 bg-card border-r border-border flex flex-col">
          {/* App Title */}
          <div className="px-4 py-6 border-b border-border">
            <h1 className="text-xl font-bold text-foreground mb-1">ssenx工具箱</h1>
            <p className="text-xs text-muted-foreground">Security & Efficiency Toolbox</p>
          </div>
          
          <div className="p-4">
            <h2 className="text-sm font-medium text-muted-foreground mb-3 uppercase">功能模块</h2>
            <nav className="space-y-1">
              <button
                onClick={() => setActiveModule("welcome")}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                  activeModule === "welcome"
                    ? "bg-primary text-primary-foreground"
                    : "text-foreground hover:bg-muted"
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                </svg>
                首页
              </button>

              <button
                onClick={handlePasswordModuleClick}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                  activeModule === "passwords"
                    ? "bg-primary text-primary-foreground"
                    : "text-foreground hover:bg-muted"
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                密码管理
              </button>

              <button
                onClick={() => setActiveModule("ai-chat")}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                  activeModule === "ai-chat"
                    ? "bg-primary text-primary-foreground"
                    : "text-foreground hover:bg-muted"
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
                </svg>
                AI对话助手
              </button>

              <button
                onClick={() => setActiveModule("ai-models")}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                  activeModule === "ai-models"
                    ? "bg-primary text-primary-foreground"
                    : "text-foreground hover:bg-muted"
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                AI模型管理
              </button>

              <button
                onClick={() => setActiveModule("settings")}
                className={`w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors ${
                  activeModule === "settings"
                    ? "bg-primary text-primary-foreground"
                    : "text-foreground hover:bg-muted"
                }`}
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
                设置
              </button>
            </nav>
          </div>

          {/* Sidebar Footer */}
          <div className="mt-auto p-4 border-t border-border">
            <div className="text-xs text-muted-foreground">
              <p className="font-medium mb-1">ssenx工具箱</p>
              <p>版本 1.0.0</p>
            </div>
          </div>
        </div>

        {/* Main Content Area */}
        <div className="flex-1 overflow-hidden p-8">
          {activeModule === "welcome" && <WelcomePage />}
          {activeModule === "passwords" && <PasswordManager />}
          {activeModule === "ai-chat" && <AIChat />}
          {activeModule === "ai-models" && <ModelManagement />}
          {activeModule === "settings" && <SettingsPage onNavigateToWelcome={() => setActiveModule("welcome")} />}
        </div>

        {/* Password Authentication Modal */}
        {(showPasswordAuth && !isLoading) && (
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4">
            {(() => {
              logger.info('[Dashboard] Modal render - hasMasterPassword: ' + hasMasterPassword);
              return !hasMasterPassword;
            })() ? (
              <div className="bg-background rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-auto">
                <div className="p-4 border-b border-border flex items-center justify-between">
                  <h2 className="text-lg font-semibold text-foreground">设置主密码</h2>
                  <button
                    onClick={() => setShowPasswordAuth(false)}
                    className="text-muted-foreground hover:text-foreground"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
                <PasswordSetup onSuccess={handleAuthSuccess} />
              </div>
            ) : (
              <div className="bg-background rounded-lg shadow-xl max-w-md w-full">
                <div className="p-4 border-b border-border flex items-center justify-between">
                  <h2 className="text-lg font-semibold text-foreground">密码管理器</h2>
                  <button
                    onClick={() => setShowPasswordAuth(false)}
                    className="text-muted-foreground hover:text-foreground"
                  >
                    <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                    </svg>
                  </button>
                </div>
                <PasswordLogin onSuccess={handleAuthSuccess} />
              </div>
            )}
          </div>
        )}
      </div>

      {/* Toast Notification */}
      {toast && (
        <div className={`fixed bottom-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 flex items-center gap-2 animate-in slide-in-from-right ${
          toast.type === "success" ? "bg-green-500 text-white" :
          toast.type === "error" ? "bg-red-500 text-white" :
          "bg-blue-500 text-white"
        }`}>
          <span>{toast.message}</span>
        </div>
      )}

      {/* Log Viewer - Press Ctrl+Shift+L to toggle or click icon in titlebar */}
      {showLogViewer && <LogViewer onClose={() => setShowLogViewer(false)} />}
    </div>
  );
}

function WelcomePage() {
  return (
    <div className="h-full overflow-auto">
      <div className="max-w-6xl mx-auto p-8">
        {/* Welcome Header */}
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-foreground mb-2">欢迎使用 ssenx 工具箱</h1>
          <p className="text-muted-foreground">安全高效的多功能工具集合 - Security & Efficiency Toolbox</p>
        </div>

        {/* Feature Cards */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8">
          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-blue-100 dark:bg-blue-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">安全加密</h3>
            <p className="text-sm text-muted-foreground">
              使用 AES-256-GCM 和 Argon2 双重加密算法，确保您的密码绝对安全
            </p>
          </div>

          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-green-100 dark:bg-green-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-green-600 dark:text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">本地存储</h3>
            <p className="text-sm text-muted-foreground">
              所有数据仅存储在您的设备上，无需担心云端泄露风险
            </p>
          </div>

          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-purple-100 dark:bg-purple-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-purple-600 dark:text-purple-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">快速便捷</h3>
            <p className="text-sm text-muted-foreground">
              一键复制、自动填充、密码生成等功能让管理密码变得轻松
            </p>
          </div>

          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-orange-100 dark:bg-orange-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-orange-600 dark:text-orange-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">开源透明</h3>
            <p className="text-sm text-muted-foreground">
              完全开源的代码，您可以审查每一行代码，确保没有后门
            </p>
          </div>

          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-pink-100 dark:bg-pink-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-pink-600 dark:text-pink-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6V4m0 2a2 2 0 100 4m0-4a2 2 0 110 4m-6 8a2 2 0 100-4m0 4a2 2 0 110-4m0 4v2m0-6V4m6 6v10m6-2a2 2 0 100-4m0 4a2 2 0 110-4m0-4v2m0-6V4" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">跨平台</h3>
            <p className="text-sm text-muted-foreground">
              支持 Windows、macOS 和 Linux，在不同设备上保持一致体验
            </p>
          </div>

          <div className="p-6 bg-card border border-border rounded-lg hover:shadow-md transition-shadow">
            <div className="w-12 h-12 bg-cyan-100 dark:bg-cyan-900/20 rounded-lg flex items-center justify-center mb-4">
              <svg className="w-6 h-6 text-cyan-600 dark:text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
              </svg>
            </div>
            <h3 className="text-lg font-semibold text-foreground mb-2">自定义分类</h3>
            <p className="text-sm text-muted-foreground">
              创建自定义分类和标签，让密码管理井井有条
            </p>
          </div>
        </div>

        {/* Quick Stats */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div className="p-6 bg-gradient-to-br from-blue-500 to-blue-600 text-white rounded-lg">
            <div className="text-3xl font-bold mb-2">AES-256</div>
            <p className="text-blue-100">军事级加密标准</p>
          </div>

          <div className="p-6 bg-gradient-to-br from-green-500 to-green-600 text-white rounded-lg">
            <div className="text-3xl font-bold mb-2">100%</div>
            <p className="text-green-100">本地离线存储</p>
          </div>

          <div className="p-6 bg-gradient-to-br from-purple-500 to-purple-600 text-white rounded-lg">
            <div className="text-3xl font-bold mb-2">开源</div>
            <p className="text-purple-100">完全透明可审计</p>
          </div>
        </div>
      </div>
    </div>
  );
}

interface SettingsPageProps {
  onNavigateToWelcome: () => void;
}

function SettingsPage({ onNavigateToWelcome }: SettingsPageProps) {
  const [dbPath, setDbPath] = useState<string>("");
  const [hideDatabase, setHideDatabase] = useState<boolean>(true);
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState<{ text: string; type: "success" | "error" } | null>(null);
  const [showChangeMasterPassword, setShowChangeMasterPassword] = useState(false);

  useEffect(() => {
    loadDbPath();
    loadHideStatus();
  }, []);

  const loadDbPath = async () => {
    try {
      const { invoke } = await import("@tauri-apps/api/core");
      const path = await invoke<string>("get_database_path");
      setDbPath(path);
    } catch (error) {
      console.error("Failed to load database path:", error);
    }
  };

  const loadHideStatus = async () => {
    try {
      const { invoke } = await import("@tauri-apps/api/core");
      const status = await invoke<boolean>("get_db_hide_status");
      setHideDatabase(status);
    } catch (error) {
      console.error("Failed to load hide status:", error);
    }
  };

  const handleToggleHide = async (checked: boolean) => {
    try {
      setIsLoading(true);
      setMessage(null);
      const { invoke } = await import("@tauri-apps/api/core");
      await invoke("set_db_hide_status", { hide: checked });
      setHideDatabase(checked);
      setMessage({ 
        text: checked ? "数据库文件已隐藏" : "数据库文件已取消隐藏", 
        type: "success" 
      });
    } catch (error) {
      setMessage({ text: `设置失败: ${error}`, type: "error" });
    } finally {
      setIsLoading(false);
    }
  };

  const handleSelectDbPath = async () => {
    try {
      const { save } = await import("@tauri-apps/plugin-dialog");
      const selected = await save({
        defaultPath: dbPath,
        filters: [
          {
            name: "SQLite Database",
            extensions: ["db", "sqlite", "sqlite3"],
          },
        ],
      });

      if (selected) {
        setIsLoading(true);
        setMessage(null);
        
        try {
          const { invoke } = await import("@tauri-apps/api/core");
          const newPath = await invoke<string>("set_database_path", { newPath: selected });
          setDbPath(newPath);
          setMessage({ text: "数据库路径设置成功！应用将使用新的数据库文件。", type: "success" });
        } catch (error) {
          setMessage({ text: `设置数据库路径失败: ${error}`, type: "error" });
        } finally {
          setIsLoading(false);
        }
      }
    } catch (error) {
      console.error("Failed to select path:", error);
      setMessage({ text: "打开文件选择器失败", type: "error" });
    }
  };

  return (
    <div className="h-full overflow-auto">
      <div className="max-w-4xl mx-auto p-8">
        <h1 className="text-2xl font-bold text-foreground mb-6">设置</h1>
        
        {message && (
          <div className={`mb-6 p-4 rounded-lg ${
            message.type === "success" ? "bg-green-100 dark:bg-green-900/20 text-green-800 dark:text-green-200" : 
            "bg-red-100 dark:bg-red-900/20 text-red-800 dark:text-red-200"
          }`}>
            {message.text}
          </div>
        )}

        <div className="space-y-6">
          {/* Database Settings */}
          <div className="bg-card border border-border rounded-lg p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4">数据库设置</h2>
            <div className="space-y-4">
              <div>
                <p className="font-medium text-foreground mb-2">数据库文件位置</p>
                <p className="text-sm text-muted-foreground mb-3">
                  当前数据库路径：
                </p>
                <div className="flex gap-2">
                  <input
                    type="text"
                    value={dbPath}
                    readOnly
                    className="flex-1 px-3 py-2 bg-muted border border-border rounded-md text-sm text-foreground"
                  />
                  <button
                    onClick={handleSelectDbPath}
                    disabled={isLoading}
                    className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isLoading ? "设置中..." : "选择路径"}
                  </button>
                </div>
                <p className="text-xs text-muted-foreground mt-2">
                  ⚠️ 更改数据库路径后，应用将使用新路径的数据库文件。如果文件不存在，将创建一个新的数据库。
                </p>
              </div>
              
              <div className="flex items-center justify-between pt-4 border-t border-border">
                <div>
                  <p className="font-medium text-foreground">隐藏数据库文件 (Windows)</p>
                  <p className="text-sm text-muted-foreground">在文件资源管理器中隐藏数据库文件以增强隐私</p>
                </div>
                <label className="relative inline-flex items-center cursor-pointer">
                  <input
                    type="checkbox"
                    checked={hideDatabase}
                    onChange={(e) => handleToggleHide(e.target.checked)}
                    disabled={isLoading}
                    className="sr-only peer"
                  />
                  <div className="w-11 h-6 bg-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
                </label>
              </div>
            </div>
          </div>

          {/* General Settings */}
          <div className="bg-card border border-border rounded-lg p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4">常规设置</h2>
            <div className="space-y-4">
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-foreground">自动锁定</p>
                  <p className="text-sm text-muted-foreground">一段时间不活动后自动锁定</p>
                </div>
                <input type="checkbox" className="w-5 h-5" />
              </div>
              
              <div className="flex items-center justify-between">
                <div>
                  <p className="font-medium text-foreground">启动时自动登录</p>
                  <p className="text-sm text-muted-foreground">记住登录状态</p>
                </div>
                <input type="checkbox" className="w-5 h-5" />
              </div>
            </div>
          </div>

          {/* Security Settings */}
          <div className="bg-card border border-border rounded-lg p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4">安全设置</h2>
            <div className="space-y-4">
              <button 
                onClick={() => setShowChangeMasterPassword(true)}
                className="w-full px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors text-left"
              >
                修改主密码
              </button>
              <button className="w-full px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 transition-colors text-left">
                导出备份
              </button>
              <button className="w-full px-4 py-2 bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/90 transition-colors text-left">
                清除所有数据
              </button>
            </div>
          </div>
          
          {/* Change Master Password Modal */}
          {showChangeMasterPassword && (
            <ChangeMasterPassword
              onClose={() => setShowChangeMasterPassword(false)}
              onSuccess={() => {
                setMessage({ text: "主密码修改成功！请使用新密码重新登录。", type: "success" });
                // Return to welcome page after password change
                onNavigateToWelcome();
              }}
            />
          )}

          {/* About */}
          <div className="bg-card border border-border rounded-lg p-6">
            <h2 className="text-lg font-semibold text-foreground mb-4">关于</h2>
            <div className="text-sm text-muted-foreground space-y-2">
              <p><strong>应用名称：</strong>ssenx工具箱</p>
              <p><strong>版本：</strong>1.0.0</p>
              <p><strong>构建：</strong>Tauri 2 + React 18</p>
              <p><strong>加密：</strong>AES-256-GCM + Argon2</p>
              <p><strong>许可：</strong>AGPL-3.0</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
